<template>
    <div class="container">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>试题录入</span>
        </div>
  
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <!-- 学科 -->
          <el-form-item label="学科:" prop="subjectID">
            <el-select
              style="width:400px;height:36px"
              v-model="formList.subjectID"
              placeholder="请选择"
              @focus="getSimpleList"
              @change="getSubjectList(ruleForm.subjectID)"
            >
              <el-option
                v-for="item in formList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
  
          <el-form-item label="目录:" prop="directoryName">
            <el-select
              style="width:400px;height:36px"
              v-model="formList.catalogID"
              placeholder="请选择"
            >
              <el-option
                v-for="(item, index) in muliSimpleList"
                :key="index"
                :label="item.directoryName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
  
          <el-form-item label="企业:" prop="company">
            <el-select
              v-model="ruleForm.company"
              placeholder="请选择"
              @change="getCompanyList(ruleForm.company)"
            >
              <el-option
                v-for="item in CompanyList"
                :key="item.number"
                :label="item.company"
                :value="item.company"
              ></el-option>
            </el-select>
          </el-form-item>
  
          <el-form-item label="城市:" prop="province">
            <el-select
              style="width:196px;height:36px"
              v-model="ruleForm.province"
              placeholder="请选择"
              @change="getdiqu"
            >
              <el-option
                v-for="item in cityList"
                :key="item.index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
  
            <el-select
              style="margin-left:10px;width:196px;height:36px"
              v-model="ruleForm.city"
              placeholder="请选择"
            >
              <el-option
                v-for="item in cityList2"
                :key="item.index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
  
          <el-form-item label="方向:" prop="direction">
            <el-select v-model="ruleForm.direction" placeholder="请选择">
              <el-option
                v-for="item in directionList"
                :key="item.index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
  
          <el-form-item label="题型:">
            <template>
              <el-radio-group v-model="ruleForm.questionType">
                <el-radio v-for="item in questionTypeList" :key="item.value" :label="item.value">
                  {{ item.label }}
                </el-radio>
              </el-radio-group>
            </template>
          </el-form-item>
  
          <el-form-item label="难度:">
            <template>
              <el-radio-group v-model="ruleForm.difficulty">
                <el-radio v-for="item in difficultyList" :key="item.value" :label="item.value">
                  {{ item.label }}
                </el-radio>
              </el-radio-group>
            </template>
          </el-form-item>
  
          <el-form-item label="题干:" prop="question">
            <quill-editor
              v-model="ruleForm.question"
              :options="editorOption"
              @blur="questionField"
            ></quill-editor>
          </el-form-item>
          <!-- 单选 -->
          <el-form-item label="选项:" v-if="ruleForm.questionType === 1">
            <template>
              <el-radio-group v-model="ruleForm.radio" @change="subcode(ruleForm.radio)">
                <el-form-item
                  v-for="item in ruleForm.options"
                  :key="item.index"
                  style="margin-top: 20px"
                >
                  <div class="flexyang" style="display:flex">
                    <div style="flex:6;margin-right:20px">
                      <el-radio :label="item.code">
                        {{ item.code }}:
                        <el-input v-model="item.title"></el-input>
                      </el-radio>
                    </div>
  
                    <div style="flex:2;margin:0">
                      <addImg
                        @fangda="filelistpost($event, item.code)"
                        :options="ruleForm.options"
                        :item="item.code"
                      />
                    </div>
                  </div>
                </el-form-item>
                <el-form-item style="margin-top: 20px">
                  <el-button type="danger" disabled><span>+增加选项与答案</span> </el-button>
                </el-form-item>
              </el-radio-group>
            </template>
          </el-form-item>
          <!--多选框 -->
          <el-form-item label="选项:" v-if="ruleForm.questionType === 2">
            <template>
              <div style="width:440px">
                <!-- @change="checkboxDom(ruleForm.options)" -->
                <el-checkbox-group
                  v-model="ruleForm.checkList"
                  @change="checkboxDom(ruleForm.checkList)"
                >
                  <el-form-item
                    v-for="(item, index) in ruleForm.options"
                    :key="index"
                    style="margin-top: 20px"
                  >
                    <div class="flexyang" style="display:flex">
                      <div style="flex:1;margin-right:5px">
                        <el-checkbox :label="item.code">
                          {{ item.code }}:
                          <el-input v-model="item.title"></el-input>
                        </el-checkbox>
                      </div>
    
                      <!-- <div>
                        <addImg
                          @fangda="filelistpost($event, item.code)"
                          :options="ruleForm.options"
                          :item="item.code"
                        />
                      </div> -->
                    </div>
                  </el-form-item>
                </el-checkbox-group>
              </div>
  
              <el-form-item style="margin-top: 20px">
                <el-button type="danger" @click="addAnswer"><span>+增加选项与答案</span> </el-button>
              </el-form-item>
            </template>
          </el-form-item>
  
          <el-form-item label="解析视频" prop="videoURL">
            <el-input v-model="ruleForm.videoURL" style="width: 300px"></el-input>
          </el-form-item>
  
          <el-form-item label="答案解析:" prop="answer">
            <quill-editor v-model="ruleForm.answer" :options="editorOption"></quill-editor>
          </el-form-item>
  
          <el-form-item label="题目备注" prop="remarks">
            <el-input
              rows="5"
              v-model="ruleForm.remarks"
              type="textarea"
              style="width:400px; "
            ></el-input>
          </el-form-item>
  
          <el-form-item label="试题标签:">
            <template>
              <el-select
                v-model="ruleForm.tags"
                multiple
                placeholder="请选择试题标签"
                allow-create
                filterable
              >
                <el-option
                  v-for="item in optionsList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label"
                >
                </el-option>
              </el-select>
            </template>
          </el-form-item>
  
          <el-form-item>
            <el-button v-if="okFine" type="primary" @click="addtianjiaAPI">
              确认提交
            </el-button>
            <el-button v-else type="primary" style="background:#67c23a" @click="addtianjiaAPI">
              确认修改
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </template>
  
  <script>
  import 'quill/dist/quill.core.css'
  import 'quill/dist/quill.snow.css'
  import 'quill/dist/quill.bubble.css'
  
  import { quillEditor } from 'vue-quill-editor'
  // import uploadImg from '@/module-hmmm/components/uploadImg/index'
  import {
    list,
    simple,
    CompanyList,
    tianjiaAPI,
    baseQuestionupdate,
    mulufuzalist,
    baseQuestiondetail
  } from '@/api/hmmm/subjects.js'
  import { list as subList} from '@/api/hmmm/directorys.js'
  import { provinces, citys } from '@/api/hmmm/citys.js'
  import { direction, questionType, difficulty, chkType } from '@/api/hmmm/constants.js'
  // import addImg from '@/module-hmmm/components/addimg/index'
  export default {
    data() {
      return {
        i: 0,
        // 富文本编辑器配置
        editorOption: {
          modules: {
            toolbar: [
              ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
              [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
              ['blockquote', 'code-block'], // 引用  代码块
              ['image', 'link'] // 链接、图片、视频
            ]
          },
          placeholder: '请输入正文'
        },
        // 列表
        ruleForm: {
          subjectID: '',
          catalogID: 0,
          enterpriseID: 0,
          province: '',
          city: '',
          direction: '',
          options: [
            { isRight: false, questionsID: '', code: 'A', title: '', img: '' },
            { isRight: false, questionsID: '', code: 'B', title: '', img: '' },
            { isRight: false, questionsID: '', code: 'C', title: '', img: '' },
            { isRight: false, questionsID: '', code: 'D', title: '', img: '' }
          ],
          question: '',
          videoURL: '',
          remarks: '',
          answer: '',
          checkList: [],
          tags: [],
          radio: null,
          questionType: 1,
          difficulty: 1,
          id: '',
          shortName: '',
          number: '',
          subjectName: '',
          directoryName: '',
          company: ''
        },
        okFine: true,
        // 图片地址
        fileUrl: '',
        // 规则
        rules: {
          subjectName: [{ required: true, message: '请选择学科', trigger: 'change' }],
          // directoryName: [{ required: true, message: '目录必填', trigger: 'change' }],
          // enterpriseID: [{ required: true, message: '企业必填', trigger: 'change' }],
          province: [
            { required: true, message: '请选择企业', trigger: 'change' },
            { validator: this.validateprovince, trigger: ['change', 'blur'] }
          ],
          direction: [{ required: true, message: '请选择方向', trigger: 'change' }],
          question: [{ required: true, message: '请输入题干' }],
          // videoURL: [{ required: true, message: '解析视频必填', trigger: ['change', 'blur'] }],
          answer: [
            [{ validator: this.validateremarks, message: '请输入题干', trigger: ['change', 'blur'] }]
          ]
          // remarks: [{ required: true, message: '题目备注必填', trigger: ['change', 'blur'] }]
        },
        subjectList: [],
        CompanyList: [],
        cityList: [],
        cityList2: [],
        directionList: direction,
        questionTypeList: questionType,
        difficultyList: difficulty,
        optionsList: chkType,
        muliSimpleList: [],
        ruleFormModel: {},
        formList:[]
      }
    },
    // watch: {
    //   'ruleForm.checkList': function(val) {
    //     console.log(val)
    //   }
    // },
    components: {
      quillEditor,
      // addImg
      // uploadImg
    },
    created() {
      this.getSimpleList()
      this.getCompanyList()
      this.getprovincesList()
      this.getmulusimple()
      this.huitain()
      this.buttonColor()
    },
  
    methods: {
      buttonColor() {
        if (this.$route.query.id) {
          this.okFine = false
        } else {
          this.okFine = true
        }
      },
  
      // 获取学科简单列表
      async getSimpleList() {
        const { data: res } = await simple()
        this.formList = res
        console.log(res)
        // console.log(this.subjectList)
      },
      // 获取学科列表
      async getSubjectList(id) {
        // this.ruleForm.directoryName = ''
        /* const {
          data: { items: res2 }
        } = await list({ pagesize: 1000 })

        /* if (this.ruleForm.subjectName) {
          this.getmulusimple(this.ruleForm.subjectName)
        } */
        // 根据学科获取目录
        const {
          data: { items: res }
        } = await subList({
          subjectID:this.formList.subjectID})
          this.muliSimpleList = res
        /* this.muliSimpleList = res.filter(item => {
          return item.subjectName === val
        }) */
      },
      // // 获取目录
      // /* async getmulusimple(val) {
      //   const {
      //     data: { items: res }
      //   } = await subList({val})
  
      //   this.muliSimpleList = res.filter(item => {
      //     return item.subjectName === val
      //   })
      //   if (this.muliSimpleList[0]) {
      //     this.ruleForm.subjectID = this.muliSimpleList[0].subjectID
      // }, */
      // 改变
      async gaicatlog(val) {
        const {
          data: { items: res }
        } = await mulufuzalist()
        console.log('目录单', val)
        console.log(res)
        const catlogidObj = res.filter(item => {
          return item.directoryName === val
        })
        this.ruleForm.catalogID = catlogidObj[0].id
      },
  
      // 获取企业列表
      async getCompanyList(val) {
        const {
          data: { items }
        } = await CompanyList({ pagesize: 1000 })
        console.log('企业', items)
  
        this.CompanyList = items
        if (val) {
          const numcom = this.CompanyList.filter(item => {
            return item.company === val
          })
          console.log(numcom)
          this.ruleForm.enterpriseID = numcom[0].id
        }
      },
      // 获取城市
      async getprovincesList() {
        const res = await provinces()
        this.cityList = res
      },
      // 获取城市中的地区
      async getdiqu() {
        const res = await citys(this.ruleForm.province)
        this.cityList2 = res
        this.ruleForm.city = ''
      },
  
      // 地区自定义校验
      validateProvince(rule, value, callback) {
        if (this.ruleForm.province === '' || this.ruleForm.city === '') {
          callback(new Error('请选择地区'))
        } else {
          callback()
        }
      },
  
      // 清空重置
      resetemp() {
        this.$refs.ruleForm.resetFields()
        this.tags = ''
        this.questionType = 1
        this.difficulty = 1
        this.ruleForm = {
          subjectID: '',
          answer: '',
          catalogID: '',
          enterpriseID: '',
          province: '',
          city: '',
          direction: '',
          options: [
            { isRight: false, code: 'A', title: '', img: '' },
            { isRight: false, code: 'B', title: '', img: '' },
            { isRight: false, code: 'C', title: '', img: '' },
            { isRight: false, code: 'D', title: '', img: '' }
          ],
          question: '',
          videoURL: '',
          remarks: ''
        }
      },
  
      // 企业自定义校验
      validateprovince(rule, value, callback) {
        if (this.ruleForm.province === '' || this.ruleForm.city === '') {
          callback(new Error('请选择地区'))
        } else {
          callback()
        }
      },
      // 题干校验
      questionField() {
        this.$refs.ruleForm.validateField('question')
      },
      // 备注自定义校验
      // validateremarks(rule, value, callback) {
      //   callback(new Error('错误'))
      // },
      // 单选
      subcode(val) {
        const codeindex = this.ruleForm.options.findIndex(item => {
          return item.code === val
        })
        this.ruleForm.options[codeindex].isRight = true
        this.ruleForm.options[codeindex].img = this.$refs.rescode
        // this.ruleForm.options[codeindex].img = this.$refs.val.filelist[0].url
      },
      // 传数据
      filelistpost([{ url }], val) {
        const codeindex = this.ruleForm.options.findIndex(item => {
          return item.code === val
        })
        this.ruleForm.options[codeindex].img = url
      },
  
      // 多选
      checkboxDom(array) {
        // console.log(array)
        const arr = []
        this.ruleForm.options.forEach(item => {
          array.forEach(item2 => {
            if (item2 === item.code) {
              item.isRight = true
            }
          })
          arr.push(item)
        })
  
        this.ruleForm.options = arr
      },
      // 随机顺序生成ABCDE...字母的函数
      setDesc() {
        const letterArr = []
        // 字母A的code值是65，但因为已经到字母D了，所以直接从69E开始循环
        for (let i = 69; i < 91; i++) {
          letterArr[i] = String.fromCharCode(i)
        }
        return letterArr
      },
  
      // 添加选项与答案
      addAnswer() {
        const randomAbc = this.setDesc().splice(70)
        const res = [
          ...this.ruleForm.options,
          { isRight: false, code: randomAbc[this.i], title: '', img: '' }
        ]
        this.i++
        this.ruleForm.options = res
      },
      // 数据回填
      async huitain() {
        if (this.$route.query.id) {
          const { data: res } = await baseQuestiondetail(this.$route.query)
          console.log('回填', res)
          this.ruleForm = res
  
          const CompanyItem = this.CompanyList.filter(item => {
            return item.id === this.ruleForm.enterpriseID
          })
          console.log('回填公司对象', CompanyItem)
          if (CompanyItem[0]) {
            this.ruleForm.company = CompanyItem[0].company
          }
  
          if (this.ruleForm.tags) {
            this.ruleForm.tags = this.ruleForm.tags.split(',')
            // console.log(ths)
          }
          if (this.ruleForm.enterpriseID) {
            console.log('789', this.CompanyList)
            const nameArry = this.CompanyList.filter(item => {
              return item.id === this.ruleForm.enterpriseID
            })
            console.log(nameArry)
            this.ruleForm.company = nameArry[0].company
            console.log(this.ruleForm.enterpriseID)
          }
          this.ruleForm.checkList = this.ruleForm.options
          this.ruleForm.questionType = +this.ruleForm.questionType
          this.ruleForm.difficulty = +this.ruleForm.difficulty
  
          if (!this.ruleForm.options[0]) {
            // options为空
            this.ruleForm.options = [
              { isRight: false, questionsID: '', code: 'A', title: '', img: '' },
              { isRight: false, questionsID: '', code: 'B', title: '', img: '' },
              { isRight: false, questionsID: '', code: 'C', title: '', img: '' },
              { isRight: false, questionsID: '', code: 'D', title: '', img: '' }
            ]
          }
          // 单选情况下
  
          // console.log(rescode)
          if (this.ruleForm.questionType === 1) {
            const rescode = this.ruleForm.options.filter(item => {
              return item.isRight === 1
            })
            console.log('单选', rescode)
            this.ruleForm.radio = rescode[0].code
          }
          if (this.ruleForm.questionType === 2) {
            const rescode = this.ruleForm.options.filter(item => {
              return item.isRight === 1
            })
            console.log('多选', rescode)
            const mapcode = rescode.map(item => {
              return item.code
            })
            console.log('code', mapcode)
            this.ruleForm.checkList = mapcode
          }
        }
      },
  
      // 提交数据
      addtianjiaAPI() {
        this.$refs.ruleForm.validate(async flag => {
          if (!flag) return
          this.ruleForm.tags = this.ruleForm.tags.join(',')
          this.ruleForm.questionType = this.ruleForm.questionType.toString()
          this.ruleForm.difficulty = this.ruleForm.difficulty.toString()
          if (this.$route.query.id) {
            // 修改
            await baseQuestionupdate(this.ruleForm)
            this.$message.success('修改成功')
          } else {
            // 添加
            await tianjiaAPI({
              ...this.ruleForm
            })
            this.$message.success('添加成功')
          }
  
          this.resetemp()
          this.$router.push('/questions/list')
        })
      }
    }
  }
  </script>
  
  <style scoped lang="scss">
  .container {
    margin: 20px;
  }
  .clearfix:before,
  .clearfix:after {
    display: table;
    content: '';
  }
  .clearfix:after {
    clear: both;
  }
  
  .box-card {
    width: 100%;
  }
  ::v-deep 
    .ql-editor {
      min-height: 200px;
    }
    .el-select {
      width: 400px;
      height: 36px;
    }
  
    .data-v-469553e3.el-button--medium {
      padding: 10px 20px;
      font-size: 12px;
      border-radius: 4px;
    }
    [data-v-469553e3] .el-button--medium {
      padding: 9px 20px;
      font-size: 12px;
      border-radius: 4px;
    }
    .yangColor {
      padding: 12px 20px;
      font-size: 15px;
      border-radius: 4px;
    }
  
  </style>
  